package com.atguigu.zqkJdbc;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Date:2020/8/28
 * Author:ybc
 * Description:
 */
public class ZqkTransactionTest {

    /*
    实现功能：创建订单
        1、添加订单信息
        2、更新图书的库存和销量
        JDBC中默认一个sql是一个事务，并且默认自动提交事务
        JDBC如何开启事务：
        connection.setAutoCommit(false);//关闭自动提交
        connection.commit();//提交事务
        connection.rollback();//回滚事务
     */
@Test
public void testTransaction(){
    Connection connection = null;
    PreparedStatement ps = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");

        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/zhang_s", "root", "123456");
        connection.setAutoCommit(false);//关闭自动提交
        ps = connection.prepareStatement("insert into t_order values(null,now(),2,320,1)");
        ps.executeUpdate();
        ps = connection.prepareStatement("update t_books set sales = sales + 1, stock = stock -1 where id in (1,2)");
        ps.executeUpdate();
        connection.commit();

    } catch (Exception e) {
        try {
            connection.rollback();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        e.printStackTrace();
    }finally {

            try {
                ps.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}


